package com.atguigu.tingshu.common.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.CompletableFuture;

@Service
public class KafkaService {

    private static final Logger logger = LoggerFactory.getLogger(KafkaService.class);

    @Autowired
    private KafkaTemplate kafkaTemplate;


    /**
     * 发送kafka消息
     *
     * @param topic 话题
     * @param data  数据
     */
    public void sendMessage(String topic, String data) {
        this.sendMessage(topic, null, data);
    }

    /**
     * 发送kafka消息
     *
     * @param topic 话题
     * @param key   键
     * @param data  数据
     */
    public void sendMessage(String topic, String key, String data) {
        CompletableFuture future = kafkaTemplate.send(topic, key, data);
        future.whenCompleteAsync((t, e) -> {
            if (e != null) {
                logger.error("【生产者】发送消息异常：{}", e);
            }else{
                logger.info("[生产者]发送消息成功");
            }
        });
    }

}
